package com.imcode;

import java.sql.*;

public class DBUtil {

    static {
        // 加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("驱动加载成功...");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接
     *
     * @return
     */
    public static Connection getConnection() {
        // 创建数据库连接（Connection）
        String url = "jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai";
        String username = "root";
        String password = "123456";
        // 获取数据库连接
        try {
            Connection conn = DriverManager.getConnection(url, username, password);
            System.out.println("获取数据库连接成功...");
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 释放资源
     * @param conn
     * @param st
     * @param rs
     */
    public static void close(Connection conn, Statement st, ResultSet rs) {
        try {
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            st.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        DBUtil.getConnection();
    }
}
